import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    Alert,
    InteractionManager
} from 'react-native';
import ImageCropPicker from 'react-native-image-crop-picker';
import StorageUser from '../lib/plugins/StorageUser';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsItem from '../components/GoodsItem';
import Explain from './Explain';
import shopService from '../lib/services/shopService';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class AgentCard extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.state = {
            imgUriList:[],
            imgDataList:[],
            price:'',
            process:'',//代办流程
            id:this.props.navigation.state.params.id || null,
            allData:{},
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getData();
                });
                              
            }).catch(err=> {
                console.log(err)
            });
    }
    // 渲染图片列表
    renderImg(){
        var list = this.state.imgUriList;
        return(
            list.map((item,i)=>{
                return(
                    <View key={i}>
                        <TouchableOpacity style={{paddingTop:10,paddingRight:10}} onPress={()=>this.selectItem(i)}>
                            <ImageWrapper style={{width:20,height:20,position:'absolute',top:0,right:0,zIndex:1000}} icon={'stop'}/>
                            <Image style={{width:70,height:70}} source={{uri:item.path}}/>               
                        </TouchableOpacity>
                        
                    </View>
                )
            })
        )
    }

    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'代办狗证'} 
                    rightIcon={'explain'}
                    rightPress={()=>this.goExplain()}
                    leftPress={()=>this.goBack()}
                    rightStyle={{marginRight:10}}/>
                <ScrollView>
                    <View style={styles.titleText}>
                        <Text>示例图:</Text>
                    </View>
                    <View  style={{flexDirection:'row',flexWrap:'wrap',paddingLeft:10,paddingBottom:10,width:width}}>
                        {this.renderImg()}
                        <TouchableOpacity onPress={()=>this.choseImg()} style={{width:70,height:70,marginTop:10}}>
                            <ImageWrapper width={70} height={70} icon={'addImg'}/>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.titleText}>
                        <Text>代办流程:</Text>
                    </View>
                    <View style={{paddingLeft:10,paddingRight:10}}>
                        <TextInput
                            style={styles.textArea}
                            underlineColorAndroid={'transparent'}
                            textAlignVertical={'top'}
                            multiline={true}
                            numberOfLines={7}
                            onChangeText={(text)=>this.getProcess(text)}
                            defaultValue={this.state.process}
                            onBlur={()=>this.editItem(2)}/>
                    </View>
                    <View style={styles.titleText}>
                        <Text>办理费用(单位:元)</Text>
                    </View>
                    <View style={{paddingLeft:10,paddingRight:10}}>
                        <TextInput
                            style={[styles.textArea,{paddingTop:0,paddingBottom:0}]}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text)=>this.getPrice(text)}
                            defaultValue={this.state.price}
                            onBlur={()=>this.editItem(3)}/>
                    </View>
                    {this.state.id?<View style={{alignItems:'center',marginTop:20,marginBottom:20}}>
                        <TouchableOpacity onPress={()=>this.editItem(1,this.state.imgDataList)}>
                            <View style={styles.button}>
                                <Text style={styles.buttonText}>修改</Text>
                            </View>
                        </TouchableOpacity>
                    </View>:<View style={{alignItems:'center',marginTop:20,marginBottom:20}}>
                        <TouchableOpacity onPress={()=>this.submitData()}>
                            <View style={styles.button}>
                                <Text style={styles.buttonText}>发布</Text>
                            </View>
                        </TouchableOpacity>
                    </View>}
                </ScrollView>
                
            </View>
        )
    }
    // 返回按钮
    goBack(){
        this.props.navigation.goBack();
    }
    // 跳转到说明页面
    goExplain(){
        const {navigate } = this.props.navigation;
        navigate('Explain')
    }
    // 如果已添加代办狗证就获取详情
    getData(){
        var $this = this;
        if(this.state.id){
            shopService.releaseAgencyIdInfo(function(data){
                // alert(JSON.stringify(data));
                if(data.code==10000){
                    var arr = [];
                    var list = [];
                    var arrList = [];
                    arr = data.data.img.split(",");
                    var len = arr.length;
                    for(var i=0;i<len;i++){
                        if(arr[i]!=''){
                            var obj = {};
                            obj.path = 'http://peita.oss-cn-beijing.aliyuncs.com/'+arr[i];
                            arrList.push(obj);
                            list.push(obj);
                        }
                        
                    }
                    $this.setState({
                        imgUriList:arrList,
                        imgDataList:list,
                        price:data.data.price,
                        process:data.data.technological_process,
                        allData:data.data,
                    })
                }
            },$this.state.id,$this.token)
        }
        
    }
    // 选择头像上传
    choseImg(){
        var $this = this;
        if(this.state.imgUriList.length>=9){
            return;
        }
        ImageCropPicker.openPicker({
                multiple: true,
                maxFiles:9,
                mediaType:'photo',
            }).then(images => {
                var len = images.length;
                var arr = [];
                for(var i=0;i<len;i++){
                    var source = {};
                    if (Platform.OS === 'android') {
                        source = {path: images[i].path, isStatic: true};
                        arr.push(source);
                    } else {
                        source = {path: images[i].path.replace('file://', ''), isStatic: true};
                        arr.push(source);
                    }
                }
                var uriArr = $this.state.imgUriList;
                var dataArr = $this.state.imgDataList;
                uriArr = uriArr.concat(arr);
                dataArr = dataArr.concat(images);
                $this.setState({
                    imgUriList:uriArr,
                    imgDataList:dataArr,
                });
            }).catch((err)=>{
                    console.log(err)
                })
                
    }
    // 获取代办流程
    getProcess(text){
        this.setState({
            process:text
        })
    }
    // 获取代办费用
    getPrice(text){
        this.setState({
            price:text
        })
    }
    // 删除图片
    selectItem(index){
        var imgList = this.state.imgUriList;
        var dataList = this.state.imgDataList;
        imgList.splice(index,1);
        dataList.splice(index,1);
        this.setState({
            imgUriList:imgList,
            imgDataList:dataList,
        })
    }
    // 调用接口提交
    submitData(){
        var $this = this;
        var imgArr = [];
        var list = this.state.imgDataList
        var len = list.length;
        for(var i=0;i<len;i++){
            imgArr['img'+(i+1)] = list[i].path;
        }
        shopService.releaseAgency(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                Alert.alert(
                    '提示信息',
                    '发布成功',
                    [{text: '确定', onPress: () => $this.goBack()}])
            }
        },$this.state.process,$this.state.price,$this.userId,imgArr,$this.token)
    }
    // 修改代办狗证
    editItem(index,list){
        var $this = this;
        if(this.state.id){
            var params = {};
            params.id = this.state.id;
            params.type = index;
            var imgArr = [];
            if(index==1){
                var len = list.length>9?9:list.length;
                var imgText = '';
                var index = 1;
                for(var i=0;i<len;i++){
                    if(/http:\/\/peita.oss-cn-beijing.aliyuncs.com\//.test(this.state.imgDataList[i].path)){
                        imgText+=this.state.imgDataList[i].path.replace(/http:\/\/peita.oss-cn-beijing.aliyuncs.com\//g,'')+',';
                    }else{
                        imgArr['img'+index] = this.state.imgDataList[i].path;
                        index++;
                    }
                    
                }
                if(len>0){
                    if(imgArr['img1']){
                        shopService.upFile(function(data){
                            alert(JSON.stringify(data));
                            if(data.code==10000){
                                params.img = imgText+data.data;
                                shopService.releaseAgencyIdSave(function(data){
                                    // alert(JSON.stringify(data));
                                    if(data.code==10000){
                                        return;
                                    }
                                },params,imgArr,$this.token)
                            }
                        },imgArr,$this.token)
                    }else{
                        params.img = imgText.substring(0,imgText.length-1);
                        shopService.releaseAgencyIdSave(function(data){
                            // alert(JSON.stringify(data));
                            if(data.code==10000){
                                return;
                            }
                        },params,imgArr,$this.token)
                    }
                    
                }
            }else if(index==2){
                if(this.state.allData.technological_process==this.state.process){
                    return;
                }
                params.technological_process = this.state.process;
                shopService.releaseAgencyIdSave(function(data){
                    // alert(JSON.stringify(data));
                    if(data.code==10000){
                        console.log('666')
                    }
                },params,imgArr,$this.token)
            }else if(index==3){
                if(this.state.allData.price==this.state.price){
                    return;
                }
                params.price = this.state.price;
                shopService.releaseAgencyIdSave(function(data){
                    // alert(JSON.stringify(data));
                    if(data.code==10000){
                        console.log('666')
                    }
                },params,imgArr,$this.token)
            }
            
        }
    }
}
const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#fff',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },
        }),
    }, 
    textArea:{
        borderWidth:1,
        borderColor:'#ccc',
        borderRadius:3
    },
    titleText:{
        height:40,
        justifyContent:'center',
        paddingLeft:10
    },
    button:{
        justifyContent:'center',
        alignItems:'center',
        height:40,
        width:3*width/4,
        backgroundColor:'#0894ED',
        borderRadius:3,
    },
    buttonText:{
        color:'#fff',
        textAlign:'center',
    }
});